from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET
from django.http import JsonResponse  # 添加这行导入
from coach.models.ai_patient_models import AIPatient
from django.contrib.auth.decorators import login_required
from coach.models import ChatRecord  # 导入聊天记录模型
from cozepy import Coze, TokenAuth, Message, COZE_CN_BASE_URL, ChatEventType
from coach.utils.ai_client import coze_client
import time, json
from django.views.decorators.http import require_POST
from django.utils import timezone
import logging
from django.http import StreamingHttpResponse  # 新增导入
import os

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_ai_patients(request):
    """
    获取AI患者数据接口
    直接返回所有患者列表，不进行分页处理
    """
    try:
        # 查询所有患者数据（按ID倒序）
        patients_queryset = AIPatient.objects.all().order_by('-id')
        
        # 格式化返回数据
        patient_list = []
        for patient in patients_queryset:
            patient_list.append({
                'id': patient.id,
                'code': patient.patient_code,
                'type': patient.patient_type,
                'bot_id': patient.bot_id,
                'created_time': patient.created_time.strftime('%Y-%m-%d %H:%M:%S'),
                'updated_time': patient.updated_time.strftime('%Y-%m-%d %H:%M:%S')
                # 可根据实际模型字段补充其他信息
            })
        
        return JsonResponse({
            'code': 200,
            'data': patient_list  # 直接返回列表，去除分页相关字段
        })
        
    except Exception as e:
        return JsonResponse({'code': 500, 'msg': f'服务器错误：{str(e)}'})

logger = logging.getLogger(__name__)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def get_ai_response(request):
    """
    学生与扣子智能体聊天接口
    请求参数：bot_id(AI患者ID), message(用户消息内容)
    返回：流式响应(Event Stream)
    """
    try:
        data = json.loads(request.body)
        patient_id = data.get('patient_id')
        message = data.get('message', '')
        user = request.user
        
        print(patient_id, message)
        print(user)
        # 参数验证
        if not patient_id or not message:
            return JsonResponse({
                'code': 400,
                'msg': '缺少patient_id或message参数'
            })

        # 获取AI患者信息
        try:
            patient = AIPatient.objects.get(id=patient_id)
            bot_id = patient.bot_id
        except AIPatient.DoesNotExist:
            return JsonResponse({
                'code': 404,
                'msg': 'AI患者不存在'
            })

        # 保存用户消息记录
        ChatRecord.objects.create(
            student=user,
            ai_patient=patient,
            sender_type='student',
            message_content=message,
            created_at=timezone.now()
        )

        # 构建流式响应
        response = StreamingHttpResponse(content_type='text/event-stream')
        response['Cache-Control'] = 'no-cache'

        def stream_response():
            ai_response_content = ""
            try:
                # 调用扣子智能体API
                for event in coze_client.chat.stream(
                    bot_id=bot_id,
                    user_id=str(user.id),
                    additional_messages=[
                        Message.build_user_question_text(message),
                    ],
                ):
                    print(event.event)
                    if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
                        if event.message:
                            ai_response_content += event.message.content
                            # 流式返回增量内容
                            yield f"data: {json.dumps({
                                'type': 'delta',
                                'content': event.message.content,
                                'code': 200
                            })}\n\n"
                    elif event.event == ChatEventType.CONVERSATION_CHAT_COMPLETED:
                        # 保存完整AI回复
                        print(ai_response_content)
                        ChatRecord.objects.create(
                            student=user,
                            ai_patient=patient,
                            sender_type='ai',
                            message_content=ai_response_content,
                            created_at=timezone.now()
                        )
                        # 返回完成标识
                        yield f"data: {json.dumps({
                            'type': 'complete',
                            'token_usage': event.chat.usage.token_count,
                            'code': 200
                        })}\n\n"
                        break

            except Exception as e:
                logger.error(f"扣子智能体调用失败: {str(e)}")
                yield f"data: {json.dumps({
                    'type': 'error',
                    'msg': f'服务器错误: {str(e)}',
                    'code': 500
                })}\n\n"

        response.streaming_content = stream_response()
        return response

    except json.JSONDecodeError:
        return JsonResponse({'code': 400, 'msg': '无效的JSON格式'})
    except Exception as e:
        logger.error(f"聊天接口异常: {str(e)}")
        return JsonResponse({'code': 500, 'msg': f'服务器错误: {str(e)}'})